package com.stardata.liangshisq.tcslmon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stardata.liangshisq.tcslmon.entity.SysParameter;
import com.stardata.liangshisq.tcslmon.mapper.SysParameterMapper;
import com.stardata.liangshisq.tcslmon.service.SysParameterService;
import com.stardata.liangshisq.tcslmon.util.JSONUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Samson Shu
 * @email shush@stardata.top
 * @date 2020/12/13 10:48
 */
@Service
@AllArgsConstructor
public class SysParameterServiceImpl extends ServiceImpl<SysParameterMapper, SysParameter>
    implements SysParameterService {
  private final SysParameterMapper sysParameterMapper;

  @Override
  public String getByCode(@NotNull String code) {
    QueryWrapper<SysParameter> wrapper = new QueryWrapper<>();
    wrapper.eq("code", code);
    List<SysParameter> list = sysParameterMapper.selectList(wrapper);
    return list.size()>0? list.get(0).getValue():null;
  }

  @Override
  public void saveByCode(@NotNull String code, @NotNull String value) {
    QueryWrapper<SysParameter> wrapper = new QueryWrapper<>();
    wrapper.eq("code", code);
    sysParameterMapper.delete(wrapper);
    SysParameter sysParameter = new SysParameter();
    sysParameter.setCode(code);
    sysParameter.setValue(value);
    sysParameterMapper.insert(sysParameter);
  }

  @Override
  @NotNull
  public  <T> List<T> getListByCode(String code, Class<T> valueType) {
    List<T> result = null;
    String str = getByCode(code);
    if (!StringUtils.isBlank(str)) {
      result = JSONUtil.parseList(str, valueType);
    }
    return (result == null)?new ArrayList<>(): result;
  }
}
